package com.zrrd.learn.chapter03;

/**
 * 二分法
 *
 * @author asus
 * @version 1.0
 * @date 2023/5/13 14:52
 */
public class BinarySearch {
    /**
     * 假如有一组有序的数
     * @param start 开始
     * @param end 结尾
     * @param target 目标
     * @return true!false
     */

    public static boolean binarySearch(int start,int end,int target) {
        checkException(start, end);
        return binarySearchReal(start,end,target);
    }
        //容错 处理
        public static void checkException(int start,int end){
        if(start>end){
            throw new RuntimeException("参数有问题");
            }

        }
        //计算功能
        private static boolean binarySearchReal(int start,int end,int target){
        if(start==end){
            return start ==target;
        }

        while(start<=end){
            int middle = end +start >> 1;
            if(middle==target){
                return true;
            }else if(middle<target){
                start = middle+1;
            }else{
                end = middle -1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(binarySearch(1,14,15));
    }
}
